package wxapp

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"net/http"
)

type Result struct {
	Openid     string `json:"openid"`
	SessionKey string `json:"session_key"`
	Unionid    string `json:"unionid"`
	Errcode    int    `json:"errcode"`
	Errmsg     string `json:"errmsg"`
}

// 微信小程序 授权登录
func GetInfo(code string) (Result, error) {
	code2sessionURL := "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
	url := fmt.Sprintf(code2sessionURL, AppID, AppSecret, code)
	resp, err := http.DefaultClient.Get(url)
	var result Result
	if err != nil {
		return result, err
	}

	if err = json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return result, err
	}
	defer resp.Body.Close()
	return result, nil
}

// -------------------------------- 微信网页授权
// GetUserinfo 用户信息
func GetUserinfo(code string) (map[string]any, error) {
	var wxMap map[string]any
	token, err := getAccessToken(code)
	if err != nil {
		return wxMap, err
	}

	code2sessionURL := "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"
	url := fmt.Sprintf(code2sessionURL, token["access_token"], token["openid"])
	resp, err := http.DefaultClient.Get(url)
	if err != nil {
		return wxMap, err
	}

	json.NewDecoder(resp.Body).Decode(&wxMap)
	if wxMap == nil {
		return wxMap, err
	}
	defer resp.Body.Close()
	return wxMap, nil
}

// 获取AccessToken
func getAccessToken(code string) (map[string]string, error) {
	var wxMap map[string]string

	code2sessionURL := "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"
	url := fmt.Sprintf(code2sessionURL, AppID, AppSecret, code)
	resp, err := http.DefaultClient.Get(url)
	if err != nil {
		log.Println("wxMap:", wxMap)
		return wxMap, err
	}

	json.NewDecoder(resp.Body).Decode(&wxMap)
	if wxMap == nil {
		return wxMap, err
	}
	if wxMap["errcode"] == "40029" {

		return wxMap, errors.New(wxMap["errmsg"])
	}

	defer resp.Body.Close()

	return wxMap, nil
}
